package com.wl.bbs.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.wl.bbs.entity.UserEx;
import com.wl.bbs.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import com.wl.bbs.entity.Result;
import com.wl.bbs.entity.User;
import com.wl.bbs.service.BizException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * BBS论坛-用户表-6 前端控制器
 * </p>
 *
 * @author ly
 * @since 2024-11-23
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    IUserService userService;

    @RequestMapping("login")
    public Result login(@Valid User user, Errors errors, HttpSession session,HttpServletResponse response) throws BizException, JsonProcessingException {
        if (errors.hasFieldErrors("uname") || errors.hasFieldErrors("upass")) {
            throw new BizException("",errors.getAllErrors());
        }
        try{
            User dbUser = userService.login(user);
            session.setAttribute("myinfo",dbUser);
            String requestURI = (String) session.getAttribute("RequestURI");
//			ObjectMapper objectMapper = new ObjectMapper();
//			String json = objectMapper.writeValueAsString(dbUser);
//			UserEx userEx = objectMapper.readValue(json, UserEx.class);
//			userEx.setRequestURI(requestURI);
            session.removeAttribute("RequestURI");
            dbUser.setRequestURI(requestURI);
            this.getAutoTime(user, response);
            return new Result(1,"登录成功",dbUser);
        } catch (BizException e){
            // 添加自定义的错误信息
            errors.rejectValue("uname", "uname or upass error", e.getMessage());
            // 给业务异常添加错误
            e.setData(errors.getAllErrors());
            throw e;
        }
    }

    @RequestMapping("myinfo")
    public Result myinfo(@SessionAttribute(required = false) User myinfo,
                         @CookieValue(required = false) String uname,
                         @CookieValue(required = false) String upass,
                         HttpSession session) throws BizException {
        if(myinfo == null){
            if(uname == null || upass == null){
                throw new BizException("未登录", null);
            } else {
                LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
                lqw.eq(User::getUname, uname);
                lqw.eq(User::getUpass, upass);
                myinfo = userService.getOne(lqw);
                session.setAttribute("myinfo", myinfo);
                // 推迟自动登录的失效时间
            }
        }
        return new Result(1, "已登录", myinfo);
    }

    @RequestMapping("seekInfo")
    public Result seekInfo(User user,HttpSession session) throws BizException {
        if(user.getUname() == null){
            return new Result(0, "未输入用户名", null);
        }else{
            if (userService.findByNa(user.getUname()) == null) {
                return new Result(0, "无该用户", user.getUname());
            }else{
                session.setAttribute("uname",user.getUname());
                return new Result(200, "查找成功", userService.findByNa(user.getUname()));
            }
        }
    }

    @RequestMapping("logout")
    public ModelAndView logout(HttpSession session ,
                               ModelAndView mav,
                               HttpServletRequest request,
                               HttpServletResponse response ){
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("uname")||cookie.getName().equals("upass") ){
                    cookie.setValue("");
                    cookie.setPath("/");
                    cookie.setMaxAge(0); // 立即过期
                    response.addCookie(cookie);
                }
            }
        }
        // TODO 退出时要删除 uname 和 upass cookie
        session.invalidate(); // 会话失效
        mav.setViewName("redirect:/index.html");
        return mav;
    }

    @PostMapping("upload")
    @ResponseBody
    public Result uploadHead(@RequestParam("head") MultipartFile file) throws IOException {
        // 获取上传的文件名
        String filename = file.getOriginalFilename();
        String prefix = UUID.randomUUID().toString();
        String suffix = filename.replaceFirst(".+\\.(\\w+)","$1");
        filename = prefix + "." + suffix;
        file.transferTo(new File("F:\\上课视频\\143\\1130\\" + filename));
        String webPath = "image/head/"+filename;
        return new Result(1,"文件上传成功", webPath);
    }

    @RequestMapping("reg")
    public Result reg(@Valid UserEx user, Errors errors) throws BizException {
        userService.reg(user,errors);
        return new Result(1,"注册成功!", null);
    }

    @RequestMapping(value = "setp")
    public Result resetP(@SessionAttribute(required = false) User myinfo, UserEx userEx) throws BizException {
        if(myinfo.getUpass() == userEx.getUpass()){
            return new Result(0,"原密码错误",null);
        }else{
            myinfo.setUpass(userEx.getUpass1());
            if(userService.setp(myinfo) >0){
                return new Result(200,"密码修改成功",myinfo);
            }else{
                return new Result(0,"密码修改失败",null);
            }
        }
    }

    @GetMapping("selectUsers")
    public List<User> selectUsers() {
        return userService.selectUsers();
    }

    @GetMapping("findMemberByQuery")
    public List<User> findMemberByQuery(
            @RequestParam(required = false) String uname,
            @RequestParam(required = false) String email,
            @RequestParam(required = false) Integer status) {
        return userService.findMemberByQuery(uname, email, status);
    }

    @RequestMapping("question")
    public Result uploadQuestion(User user, Errors errors) throws BizException {
        userService.uploadQuestion(user, errors);
        return new Result(1, "添加成功", null);
    }

    @RequestMapping("updateHead")
    public Result updateHead(@SessionAttribute(required = false) User myinfo,String head) throws BizException {
        if(myinfo==null){
            throw new BizException("未登录",null);
        }
        int result = userService.updateHead(myinfo, head);
        if(result<=0){
            return new Result(500,"修改头像错误",null);
        }
        return new Result(200,"修改头像成功",null);
    }

    @RequestMapping("resetp")
    public Result resetp(User user,HttpSession session){
        user.setUname((String) session.getAttribute("uname"));
        if(userService.setp(user) >0){
            return new Result(200,"重置密码成功",user);
        }else{
            return new Result(0,"修改失败",null);
        }
    }

    @PostMapping("confirmq")
    public Result confirmq( User user){
        User user1 = userService.findByNa(user.getUname());
        return new Result(200,"",user1);
    }

    @RequestMapping("getQuestion")
    public Result getQuestion() throws BizException {
        User question = userService.getQuestion();
        return new Result(1, null, question);
    }

    @PostMapping("auto")
    public String getAutoTime(User userDto,
                              HttpServletResponse response){
        // 自动登录的安全问题

        Cookie cookie1 = new Cookie("uname", userDto.getUname());
        Cookie cookie2 = new Cookie("upass",userDto.getUpass());
        cookie1.setPath("/");
        cookie2.setPath("/");
        switch (userDto.getAutoTime()) {
            case 1:
                cookie1.setMaxAge(24*60*60);
                cookie2.setMaxAge(24*60*60);
                break;
            case 2:
                cookie1.setMaxAge(7*24*60*60);
                cookie2.setMaxAge(7*24*60*60);
                break;
            case 3:
                cookie1.setMaxAge(30*24*60*60);
                cookie2.setMaxAge(30*24*60*60);
                break;
            default:
                return "";
        }
        response.addCookie(cookie1);
        response.addCookie(cookie2);
        return "redirect:/index.html";
    }
}